<template>
  <div id="app">
    <h1>图书管理</h1>
    <el-form ref="form" model="form" inline>
      <el-form-item label="书名">
        <el-input v-model="form.bookname"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="form.author"></el-input>
      </el-form-item>
      <el-form-item label="出版社">
        <el-input v-model="form.publisher"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="find">查询</el-button>
        <el-button
          type="primary"
          @click="
            title = '新增图书';
            dialogVisible = true;
          "
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="tableDate">
      <el-table-column prop="bookname" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="publisher" label="出版社"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelte(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="书名" prop="bookname">
          <el-input v-model="ruleForm.bookname"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="ruleForm.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="ruleForm.publisher"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogVisible = false;
            handleClose();
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm('ruleForm')">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      ruleForm: {},
      rules: {
        bookname: [
          { required: true, message: "请输入图书名字", trigger: "blur" },
        ],
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        publisher: [
          { required: true, message: "请输入出版社", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      form: {},
      tableDate: [
        {
          id: 1,
          bookname: "java编程思想",
          author: "黑马程序员",
          publisher: "黑马出版社",
        },
        {
          id: 2,
          bookname: "java编程思想",
          author: "黑马程序员",
          publisher: "黑马出版社",
        },
        {
          id: 3,
          bookname: "java编程思想",
          author: "黑马程序员",
          publisher: "黑马出版社",
        },
      ],
    };
  },
  methods: {
    handleClose() {
      this.ruleForm = {};
      this.dialogVisible = false;
    },
    find() {
      this.$message.success("查询数据成功");
    },
    handleEdit(index, row) {
      console.log(index, row);
      //目标：点击编辑按钮弹出修改对话框并显示修改数据
      //1.设置title值为“修改图书”
      this.title = "修改图书";
      //2.获取当前行数据对象row,复制封装给新this.ruleForm对象(赋值属性值，不会产生内存引用)
      this.ruleForm = {
        id: row.id,
        bookname: row.bookname,
        author: row.author,
        publisher: row.publisher,
      };
      //3.设置对话框展现dialogVisib=true
      this.dialogVisible = true;
    },
    handleDelte(index, row) {
      console.log(index, row);
      //目标删除点击事件
      //1.弹出确认取消提示框
      this.$confirm("是否继续删除文件", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //2.点击确定，进行删除操作,获取当前行书的id = row.id
          let bookId = row.id;
          //3.异步调用后端删除接口删除数据
          await axios.delete(
            "https://mock.apifox.com/m1/3792071-0-default/api/books/" + bookId
          );
          //4.删除成功后，更新tableData删除对应index位置的数据
          this.tableDate.splice(index, 1);
          //5.提示删除成功
          this.$message({
            type: "success",
            message: "删除成功",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // axios.getList().then(response{response.date.date}),
    async getList() {
      const response = await axios.get(
        "https://mock.apifox.com/m1/3792071-0-default/api/books"
      );
      this.tableDate = response.data.data;
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valia) => {
        if (valia) {
          if (this.ruleForm.id) {
            //目标：id有效进来做修改
            //1.将页面的数据ruleForm赋值给新对象book对象
            let book = {
              id: this.ruleForm.id,
              bookname: this.ruleForm.bookname,
              author: this.ruleForm.author,
              publisher: this.ruleForm.publisher,
            };
            console.log(book);
            //2.对话框内容清空
            this.$refs["ruleForm"].resetFields();
            //3.隐藏对话框
            this.dialogVisible = false;
            //4.将book数据更新到this.tableData对应行数据里面
            //  分析：遍历tableData每个元素，每个元素的id与book对象id一样进行更新数据
            this.tableDate.forEach((item) => {
              if (item.id == book.id) {
                item.bookname = book.bookname;
                item.author = book.author;
                item.publisher = book.publisher;
                return;
              }
            });
            //5.提示修改成功
            this.$message.success("修改成功");
          } else {
            //id无效则进行新增
            await axios.post(
              "https://mock.apifox.com/m1/3792071-0-default/api/books",
              this.ruleForm
            );
            let book = {
              id: Date.now(),
              bookname: this.ruleForm.bookname,
              author: this.ruleForm.author,
              publisher: this.ruleForm.publisher,
            };
            this.dialogVisible = false;
            this.$refs["ruleForm"].resetFields();
            this.tableDate.push(book);
            this.$message.success("添加成功");
          }
        } else {
          this.$message.error("校验不成功");
          return false;
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style></style>
